package com.share.config.kafka;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.listener.BatchLoggingErrorHandler;
import org.springframework.kafka.listener.ContainerProperties;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@EnableKafka
@Configuration
public class KafkaConfiguration {
    /**
     * 不规则配置---配置
     */
    @Value(value = "${spring.kafka.bootstrap-servers}")
    private String bootstrapAddress;
    @Value(value = "${spring.kafka.listener.concurrency}")
    private Integer concurrency;
    @Value(value = "${spring.kafka.listener.ack-mode}")
    private String ackMode;

    /**
     * 下面是-生产者---配置
     */

    @Value(value = "${spring.kafka.producer.retries}")
    private String retries;


    /**
     * 下面是-消费者---配置
     */

    @Value(value = "${spring.kafka.consumer.fetch-min-size}")
    private String fetchMinSize;
    @Value(value = "${spring.kafka.consumer.fetch-max-wait}")
    private String fetchMaxWait;
    @Value(value = "${spring.kafka.consumer.properties.max.poll.interval.ms}")
    private String maxPollInterval;
    @Value(value = "${spring.kafka.consumer.enable-auto-commit}")
    private boolean enableAutoCommit;
    @Value(value = "${spring.kafka.consumer.auto-offset-reset}")
    private String autoOffsetReset;
    @Value(value = "${spring.kafka.consumer.max-poll-records}")
    private String maxPollRecords;

    public Map<String, Object> consumerConfigs() {
        Map<String, Object> map = new HashMap<>();
        map.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
        map.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, Integer.parseInt(fetchMinSize));
        map.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, Integer.parseInt(fetchMaxWait));
        map.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit);
        map.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
        map.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, Integer.parseInt(maxPollInterval));
        map.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, Integer.valueOf(maxPollRecords));

        map.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        map.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return map;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        Map<String, Object> config = consumerConfigs();
        log.info("kafka消费端配置={}", JSON.toJSON(config));
        return new DefaultKafkaConsumerFactory<>(config);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(concurrency);
        factory.setBatchListener(true);//批量消费开关
        factory.setBatchErrorHandler(new BatchLoggingErrorHandler());
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.valueOf(ackMode));
        return factory;
    }


    public Map<String, Object> producerConfigs() {
        Map<String, Object> map = new HashMap<>();
        map.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
        map.put(ProducerConfig.RETRIES_CONFIG, retries);

        map.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        map.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return map;
    }

    public ProducerFactory<String, String> producerFactory() {
        Map<String, Object> config = consumerConfigs();
        log.info("kafka生产端配置={}", JSON.toJSON(config));
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<String, String>(producerFactory());
    }
}
